package com.ai.aliyun.util;

/**
 * @author: MrHe
 * @create: 2023-11-30 22:03
 * @description:
 **/

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ai.module.chat.config.properties.AliyunProperty;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.URL;
import java.util.Date;

@Slf4j
public class AliyunUtil {

    private static Client getCipClient() throws Exception {
        AliyunProperty aliyunProperty = getAliyunOssCip();
        String accessKeySecret = aliyunProperty.getAccessKeySecret();
        String accessKeyId = aliyunProperty.getAccessKeyId();
        Config cipConfig = new  Config();
        cipConfig.setAccessKeyId(accessKeyId);
        cipConfig.setAccessKeySecret(accessKeySecret);
        cipConfig.setRegionId(aliyunProperty.getCipRegionId());
        cipConfig.setEndpoint(aliyunProperty.getCipChinaEndPoint());
        return new Client(cipConfig);
    }

    private static OSS getOssClient() {
        AliyunProperty aliyunProperty = getAliyunOssCip();
        String accessKeySecret = aliyunProperty.getAccessKeySecret();
        String accessKeyId = aliyunProperty.getAccessKeyId();
        CredentialsProvider ossCredentialsProvider =
                new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        return  new OSSClientBuilder().build(aliyunProperty.getOssChinaEndPoint(), ossCredentialsProvider);
    }


    public static void createOSSBucket() {
        OSS ossClient = getOssClient();
        try {
            // 创建OSS存储空间。
            AliyunProperty aliyunProperty = getAliyunOssCip();
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliyunProperty.getOssBucketName());
            ossClient.createBucket(createBucketRequest);
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static PutObjectResult uploadOSSFile(String objectName, File file) {
        OSS ossClient = getOssClient();
        try {
            AliyunProperty aliyunProperty = getAliyunOssCip();
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunProperty.getOssBucketName(), objectName, file);
            return ossClient.putObject(putObjectRequest);
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String downloadOSSFile(String objectName) {
        OSS ossClient = getOssClient();
        AliyunProperty aliyunProperty = getAliyunOssCip();
        try {
            OSSObject ossObject = ossClient.getObject(aliyunProperty.getOssBucketName(), objectName);
            InputStream content = ossObject.getObjectContent();
            StringBuilder contentBuilder = new StringBuilder();

            if (content != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(content))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        contentBuilder.append(line);
                        contentBuilder.append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    content.close();
                    if (ossClient != null) {
                        ossClient.shutdown();
                    }
                }
            }

            return contentBuilder.toString();
        } catch (OSSException | ClientException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String generatePresignedURL(String objectName, long expirationTimeMillis) {
        OSS ossClient = getOssClient();
        AliyunProperty aliyunProperty = getAliyunOssCip();
        try {
            Date expiration = new Date(System.currentTimeMillis() + expirationTimeMillis);
            URL url = ossClient.generatePresignedUrl(aliyunProperty.getOssBucketName(), objectName, expiration);
            return url.toString();
        } catch (OSSException | ClientException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static String textModeration(String content) throws Exception {
        Client cipClient = getCipClient();
        try {
            JSONObject serviceParameters = new JSONObject();
            serviceParameters.put("content", content);

            TextModerationRequest textModerationRequest = new TextModerationRequest();
            textModerationRequest.setService("ai_art_detection");
            textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
            RuntimeOptions runtime = new RuntimeOptions();
            runtime.readTimeout = 10000;
            runtime.connectTimeout = 10000;
            TextModerationResponse response = cipClient.textModerationWithOptions(textModerationRequest, runtime);

            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        return "Labels: " + data.getLabels() + "\nReason: " + data.getReason();
                    } else {
                        return "Text moderation not successful. Code: " + code;
                    }
                } else {
                    return "Response not successful. Status: " + response.getStatusCode();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @NotNull
    private static AliyunProperty getAliyunOssCip() {
        AliyunProperty aliyunProperty = new AliyunProperty();

        aliyunProperty.setAccount("xx");
        aliyunProperty.setAccessKeyId("LTAI5tEiUhEpp6iWSUaJBRTh");
        aliyunProperty.setAccessKeySecret("Bc5hGlLCz1jPEjBtx1Ct3DUVHLTqTU");
        aliyunProperty.setOssBucketName("mrhe-loadCookie-bucket-1");
        aliyunProperty.setCipRegionId("cn-shenzhen");
        aliyunProperty.setCipForeignEndpoint("xx");
        aliyunProperty.setCipChinaEndPoint("xx");
        aliyunProperty.setOssChinaEndPoint("xx");
        return aliyunProperty;
        //return SpringUtils.getClazz(AliyunOssCip.class);
    }


    public static void main(String[] args) throws Exception {

        // 上传文件到OSS
      //  File fileToUpload = new File("H:\\code\\project\\chatgpt\\chat-start\\src\\loadCookie\\java\\com\\chat\\example.txt");
      //  PutObjectResult uploadResult = AliyunUtil.uploadOSSFile("example.txt", fileToUpload);
      //  if (uploadResult != null) {
      //      System.out.println("Upload successful");
      //  } else {
      //      System.out.println("Upload failed");
      //  }
//
      //  // 下载文件
      //  String downloadedContent = AliyunUtil.downloadOSSFile("example.txt");
      //  System.out.println("Downloaded content:\n" + downloadedContent);
//
      //  // 生成OSS预签名URL
      //  String presignedURL = AliyunUtil.generatePresignedURL("example.txt", 3600 * 1000);
      //  System.out.println("Presigned URL: " + presignedURL);

        // 文本审核
        String contentToModerate = "裸体妹子";
        String moderationResult = AliyunUtil.textModeration(contentToModerate);
        System.out.println("Moderation result:\n" + moderationResult);

    }
}

